import { useParams, useNavigate } from 'react-router-dom';
import { Form, Input, Button, Select, DatePicker, message, Spin } from 'antd';
import { scheduleService } from '../../services/schedule.service';
import { useEffect, useState } from 'react';
import type { ScheduledTask } from '../../services/schedule.service';
import moment from 'moment';

export default function ScheduleDetail() {
  const [form] = Form.useForm();
  const { id } = useParams();
  const [task, setTask] = useState<ScheduledTask | null>(null);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  const loadData = async () => {
    try {
      if (!id) return;
      const data = await scheduleService.findById('id', id);
      setTask(data);
      form.setFieldsValue({
        ...data,
        next_run: moment(data.next_run),
        parameters: data.parameters || {}
      });
    } catch (error) {
      message.error('加载任务详情失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      await scheduleService.update(id!, {
        ...values,
        next_run: values.next_run.format('YYYY-MM-DD HH:mm:ss')
      });
      message.success('更新成功');
      navigate('/schedule/list');
    } catch (error) {
      message.error('更新失败');
    }
  };

  useEffect(() => {
    loadData();
  }, [id]);

  if (loading) return <Spin size="large" />;
  if (!task) return <div>任务不存在或已被删除</div>;

  return (
    <div style={{ padding: 24, maxWidth: 600 }}>
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={task || undefined}
      >
        <Form.Item
          label="任务名称"
          name="name"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="下次执行时间"
          name="next_run"
          rules={[{ required: true }]}
        >
          <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
        </Form.Item>

        <Form.Item
          label="执行工具"
          name={['parameters', 'tool']}
          rules={[{ required: true }]}
        >
          <Select
            options={[
              { label: '数据同步工具', value: 'data_sync' },
              { label: '通知工具', value: 'notification' }
            ]}
          />
        </Form.Item>

        <Button type="primary" htmlType="submit">
          保存更改
        </Button>
      </Form>
    </div>
  );
} 